<?php
/**
 * 阿里云市场银行卡三要素验证
 *
 * @date    2020-06-23 13:56:05
 * @version $Id$
 */

namespace App\Services\Ali;

use GuzzleHttp\Client;
use GuzzleHttp\Psr7;
use App;

class AliCloudService
{
    protected $client;
    public function __construct()
    {
        $this->client = new Client(
            [
                'base_uri' => 'https://tbank.market.alicloudapi.com',
                'timeout' => 15, //秒
                'debug' => false,
                'headers' => [
                    'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
                    'Accept' => 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                    'Accept-Language' => 'zh-CN,zh;q=0.9,en;q=0.8,sm;q=0.7',
                    'Accept-Encoding' => 'gzip',
                    'Authorization' => "APPCODE ff2d0ca683c44d98bbbfd687c5deedf0",
                ],
            ]
        );
    }

    public function checkCard(string $accountNo, string $idCard, string $name) : array
    {
        if (!App::isProduction()) {
            return [
                'bank' => '惠州银行',
                'province' => '广东省',
                'city' => '惠州市'
            ];
        }
        $utf8_body = $this->request($accountNo, $idCard, $name);
        $result = json_decode($utf8_body, true);

        throw_on(
            $result['status'] !== '01',
            0xf000b2
        );

        return $result;
    }

    private function request(string $accountNo, string $idCard, string $name): string
    {
        $url = "/bank3CheckNew?accountNo={$accountNo}&idCard={$idCard}&name={$name}";
        $response = $this->client->request('get', $url);
        $type = $response->getHeader('content-type');
        $parsed = Psr7\parse_header($type);
        $original_body = (string)$response->getBody();
        return mb_convert_encoding($original_body, 'UTF-8', $parsed[0]['charset'] ?: 'UTF-8');
    }
}
